package com.kingdee.eas.custom.buscostcount.handler;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.bos.workflow.WfException;
import com.kingdee.bos.workflow.service.EnactmentServiceProxy;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.buscostcount.BusCostCountFactory;
import com.kingdee.eas.custom.buscostcount.BusCostCountInfo;
import com.kingdee.eas.custom.buscostcount.IBusCostCount;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.eas.hr.base.HRBillStateEnum;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.base.syssetting.app.filter.HRFilterUtils;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import com.kingdee.shr.base.syssetting.web.handler.EditHandler;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;
import com.kingdee.util.StringUtils;

public class BusCostCountHandler extends EditHandler {
	private static Logger logger = Logger
			.getLogger("com.kingdee.eas.custom.buscostcount.handler.BusCostCountHandler");

	private Context ctx;

	public BusCostCountHandler(Context ctx) {
		this.ctx = ctx;
	}

	public BusCostCountHandler() {
		this.ctx = SHRContext.getInstance().getContext();
	}

	/**
	 * 
	 * <p>
	 * Title: getDeptAction
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @throws SHRWebException
	 */
	// 选择姓名，带出部门
	@SuppressWarnings("unchecked")
	public void getDeptAction(HttpServletRequest request,
			HttpServletResponse response, ModelMap model)
			throws SHRWebException {

		String id = request.getParameter("id");
		// 组织
		String orgName = null;
		// 组织id
		String orgId = null;
		Map map = new HashMap();

		Map dept = new HashMap();
		StringBuffer sql = new StringBuffer();

		sql
				.append(
						"SELECT org.fid as id ,org.fname_l2 as name FROM T_ORG_POSITIONMEMBER personStion")
				.append(
						" left join T_ORG_Position pos on personStion.FPOSITIONID=pos.fid left join T_ORG_ADMIN org on pos.FADMINORGUNITID =org.fid")
				.append(
						" where personStion.FISPRIMARY =1 and personStion.fpersonid=")
				.append("'" + id + "'");

		System.out.println("============sql:" + sql.toString() + "===========");

		IRowSet rowSet = null;

		try {
			rowSet = DbUtil.executeQuery(ctx, sql.toString());
			while (rowSet.next()) {
				orgName = rowSet.getString("name");
				orgId = rowSet.getString("id");
				if (orgName != null && !"".equals(orgName) && orgId != null
						&& !"".equals(orgId)) {
					dept.put("id", orgId);
					dept.put("name", orgName);
					
					System.out.println("===========dept所属组织:" + dept + "===========");
					map.put("dept", dept);
				}
			}

		} catch (BOSException e) {
			logger.error("系统有误，请和管理员联系...");
		} catch (SQLException e) {
			logger.error("系统有误，请和管理员联系...");
		}
		JSONUtils.SUCCESS(map);
	}

	@SuppressWarnings("unchecked")
	public void canSubmitEffectAction(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap)
			throws SHRWebException {
		Map map = new HashMap();
		map.put("state", "success");
		JSONUtils.writeJson(response, map);

	}

	/**
	 * 提交生效
	 * 
	 * @description
	 *@params
	 *@return
	 */
	public void submitEffectAction(HttpServletRequest req,
			HttpServletResponse res, ModelMap modelMap) throws SHRWebException {

		CoreBaseInfo model = (CoreBaseInfo) req.getAttribute("dynamic_model");
		try {
			IBusCostCount iBusCostCount = BusCostCountFactory
					.getRemoteInstance();
			IObjectPK objectPK = iBusCostCount.submitEffect(model);
			model.setId(BOSUuid.read(objectPK.toString()));
		} catch (EASBizException e) {
			throw new SHRWebException(e.getMessage());
		} catch (Exception e) {
			throw new ShrWebBizException(e.getMessage());
		}

		System.out.println("班车费变动情况核算表id：" + model.getId().toString());

		writeSuccessData(model.getId().toString());
	}

	@Override
	protected void beforeSave(HttpServletRequest request,
			HttpServletResponse response, CoreBaseInfo model)
			throws SHRWebException {
		super.beforeSave(request, response, model);
		BusCostCountInfo bill = (BusCostCountInfo) model;
		bill.setBillState(HRBillStateEnum.SAVED);
	}

	@Override
	protected void beforeSubmit(HttpServletRequest request,
			HttpServletResponse response, CoreBaseInfo model)
			throws SHRWebException {
		super.beforeSubmit(request, response, model);

		BusCostCountInfo bill = (BusCostCountInfo) model;

		String userID = HRFilterUtils.getCurrentUserId(ctx);
		String functionName = "com.kingdee.eas.custom.atsexc.app.AtsExceptionBillEditUIFunction";
		String operationName = "actionSubmit";
		try {
			String temp = EnactmentServiceProxy.getEnacementService(ctx)
					.findSubmitProcDef(userID, bill, functionName,
							operationName);
			if ((temp == null) || (temp.trim().equals("")))
				throw new ShrWebBizException("没有可用的入职工作清单工作流");
		} catch (WfException e) {
			throw new SHRWebException(e.getMessage());
		} catch (BOSException e) {
			throw new SHRWebException(e.getMessage());
		}

		bill.setBillState(HRBillStateEnum.SUBMITED);
		String operateStatus = request.getParameter("operateState");
		if ((StringUtils.isEmpty(operateStatus))
				|| (!("ADDNEW".equalsIgnoreCase(operateStatus)))) {
			return;
		}
		bill.setExtendedProperty("isAddNew", "isAddNew");
	}

}
